<?php

namespace app\common\model\company;

use app\api\controller\Pub;
use app\common\model\coll\Collection;
use app\common\model\company\Company;
use app\common\model\cost\Costtype;
use app\common\model\orderhawa\Hawa;
use app\common\model\orderhawa\HawaList;
use app\common\model\power\Rolepower;
use app\common\model\user\User;
use app\common\model\revenue_ap\Raplist;
use think\Model;

class Contract extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'contract';
    protected $pk    = 'ContractId';

    const STATEINT     = 0; //初始化
    const STATECONFRIM = 1; //用户确认
    const STATEOK      = 2; //没问题的
    const STATEDELETE  = 404; //被删除的订单
    const STATEARRAY   = [['待完善', '已完善'], ['用户确认', '已确认'], ['会计审核', '已审核']];

    public function bussinfo()
    {
        return $this->hasOne('app\common\model\user\User', 'UserId', 'BussinessId');
    }

    public function companyinfo()
    {
        return $this->hasOne('app\common\model\company\Company', 'CompanyId', 'CompanyId');
    }

   

    public function contractDetails()
    {
        return $this->hasMany(ContractDetails::class, 'ContractId', 'ContractId');
    }

    /**
     * 状态分类
     * @param string $value [description]
     * @return [type]        [description]
     */
    public static function getStatusText($value = '')
    {
        $status = [-1 => '全部合同', 0 => '待确认', 1 => '待审核', 2 => '已通过'];
        if ($value !== '') {
            if ($value == Contract::STATEDELETE) {
                return '删除信息';
            }
            return $status[$value];
        }
        return $status;
    }

    /**
     * 创建合同信息
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function screate($data)
    {
        if (empty($data['CompanyId'])) {
            return moerr('缺少重要参数');
        }
        if (empty($data['ContractCost'])) {
            return moerr('请输入合同费用');
        }

        $userlogininfo = Pub::getuserid();
        $userid        = $userlogininfo['msg'];
        //判断是否连续触发
        $sb = Contract::where('BussinessId', $userid)->where('CompanyId', $data['CompanyId'])->where('CreateTime', '>', date('Y-m-d H:i', time() - 60))->find();
        if (!empty($sb)) {
            return serr('在一分钟内您已与产废单位签订合同，请于一分钟后尝试提交。');
        }

        $contract                = new Contract();
        $contract->PrintPassword = md5(time() . 'contract' . $data['CompanyId'] . time() . $userid . time() . $data['ContractCost']);
        $contract->BussinessId   = $userid;
        $filed                   = ['OrderNumber', 'CompanyId', 'StartTime', 'EndTime', 'ContractCost', 'UpImg', 'UpNote', 'PartyAContact', 'PartyAContactMobile', 'PartyBMailingAddress', 'PartyBContact', 'PartyBContactMobile', 'Identifier', 'Name', 'Address', 'Mobile', 'Bank', 'BankNum', 'BankCode', 'UniversalDisposal', 'DisposalFee', 'DefaultPrice', 'ShipNum', 'ShipMoney', 'SettleRemark', 'PartyAMailingAddress','TempId'];
        foreach ($filed as $key => $value) {
            if (!empty($data[$value])) {
                $contract->$value = $data[$value];
            }
        }
        
        $ordernumber = Contract::contract_ordernumber_control();
        //前端合同控制逻辑
        if(!empty($ordernumber)){
            $contract->OrderNumber = $ordernumber;
        }

        //设置余额抵扣量
        $dfile = ['ShipNum', 'UniversalDisposal', 'DisposalFee'];
        foreach ($dfile as $key => $value) {
            if (!empty($data[$value])) {
                $nvalue            = 'Surplus' . $value;
                $contract->$nvalue = $data[$value];
            }
        }

        //判断是否有绑定用户，若没绑定直接跳转到待会计确认页面
        $companyinfo = Company::get($data['CompanyId']);
        if (empty($companyinfo['UserId'])) {
            $contract->State = Contract::STATECONFRIM;
        } else {
            $contract->State = Contract::STATEINT;
        }

        //乙方财务信息
        $col = Collection::where('CompanyId', Collection::SELFCOMPANYID)->where('State', Collection::STATEOK)->find();
        if (!empty($col)) {
            $contract->PartyBBank       = $col->CardName;
            $contract->PartyBCardNumber = $col->CardNumber;
            $contract->PartyBName       = $col->UserName;
        }

        $contract->CreateTime = date('Y-m-d H:i', time());
        $contract->save();

        $sb = ContractDetails::screate($contract->ContractId, $data);
        return sok($contract);
    }
    /**
     * 获取合同编号
     * @param  [type] $arr [description]
     * @return [type]      [description]
     */
    public static function contract_ordernumber_control(){
        $arr = get_config_value('contract_ordernumber_control');
        $str = '';
        if(!empty($arr)){
            foreach ($arr as $key => $value) {
                switch ($value[0]) {
                    case 'text':
                        $str = $str.$value[1];
                        break;
                    case 'data':
                        $str = $str.date($value[1],time());
                        break;
                    case 'count':
                        if($value[1]=='day'){
                            $count = Contract::where('CreateTime','>',date('Y-m-d',time()))->count();
                        }else if($value[1]=='month'){
                            $count = Contract::where('CreateTime','>',date('Y-m',time()))->count();
                        }else if($value[1]=='year'){
                            $count = Contract::where('CreateTime','>',date('Y',time()))->count();
                        }else{
                            return moerr('合同编号获取失败：合同数设置出错');
                        }
                        $count++; 
                        if(empty($value[2])){
                            $str = $str .$count;
                        }else{
                            $str = $str.sprintf("%0".$value[2]."d",$count);
                        }
                        break;
                    default:
                            return moerr('合同编号获取失败：合同数设置出错');
                        break;
                }
            }
            return  $str;
        }
    }

    /**
     * [getcompanylist description]
     * @param  [type] $company_id [description]
     * @param  [type] $type       [description]
     * @return [type]             [description]
     */
    public static function ordergetbindcontractlist($contractId)
    {
        $data['where'][] = ['ContractId', $contractId];
        $data['where'][] = ['State', Contract::STATEOK];
        $data['order']   = 'ContractId desc';
        return Contract::usergetlist($data, 'hawaorder', false);
    }

    /**
     * [getcompanylist description]
     * @param  [type] $company_id [description]
     * @param  [type] $type       [description]
     * @return [type]             [description]
     */
    public static function getcompanycontractlist($company_id,$type='hawaorder')
    {
        $data['where'][] = ['CompanyId', $company_id];
        $data['where'][] = ['State', Contract::STATEOK];
        $data['order']   = 'ContractId desc';
        return Contract::usergetlist($data, $type, false);
    }

    /**
     * 获取合同列表
     * @param  [type] $data    [主数据]
     * @param string $type [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function deadlinelist($data, $type = 'buss', $is_page = true)
    {
        $rdata  = Contract::where('State', '<>', Contract::STATEDELETE);
        $prdata = Contract::where('State', '<>', Contract::STATEDELETE); //获取分页数据
        // $userinfo = User::getinfo();
        if ($type == 'buss') {
            $data['where'][] = ['BussinessId', Pub::userid()];
        }
        //取出最大合同id
        $rdata         = $rdata->group('CompanyId');
        $data['field'] = ['max(ContractId)' => 'ContractId', 'max(EndTime)' => 'EndTime'];
        $data['order'] = 'EndTime asc';
        $option        = come_model_option($data, $rdata, false);
        $pageoption    = come_model_option($data, $prdata, false);
        $rdata         = $option['rdata'];
        $data          = $option['data'];
        $count         = $pageoption['rdata']->count();

        if ($is_page) {
            $data['pageindex'] = empty($data['pageindex']) ? 1 : $data['pageindex'];
            $data['count']     = ceil($count / PUBLICSELECTLIMIT);
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
            $idarr             = $rdata->limit(PUBLICSELECTLIMIT)->page($data['pageindex'])->column('ContractId');
        } else {
            $idarr = $rdata->column('ContractId');
        }
        //查询实际数据
        $rdata              = Contract::where('ContractId', 'in', $idarr)->with('companyinfo,bussinfo');
        $rdata              = $rdata->visible(['EndTime', 'deadlineday', 'CompanyId', 'ContractId', 'State', 'BussinessId', 'bussinfo.Name', 'companyinfo.Name'])->order('EndTime asc')->select();
        $ndata['list']      = $rdata->toArray();
        $ndata['statetext'] = Contract::getStatusText();
        foreach ($ndata['list'] as $key => $value) {
            $ndata['list'][$key]['deadlineday'] = intval((strtotime($value['EndTime']) - time()) / 86400);
        }
        // $goodid = get_array_id($ndata,'GoodId','list','listinfo');

        // dump($data);
        return $ndata;
    }

    /**
     * 获取合同列表
     * @param  [type] $data    [主数据]
     * @param string $type [查询类型/hawa/buss]
     * @param  [type] $is_page [是否分页显示]
     * @return [type]          [description]
     */
    public static function usergetlist($data, $type = 'buss', $is_page = true)
    {
        $rdata    = Contract::where('State', '<>', Contract::STATEDELETE);
        $userinfo = User::getinfo();
        $rdata    = $rdata->with('bussinfo');
        $visible  = ['ContractId', 'CompanyId', 'OrderNumber', 'CreateTime', 'StartTime', 'EndTime', 'State', 'BussinessId'];
        if ($type == 'buss') {
            $rdata   = $rdata->where('BussinessId', Pub::userid());
            $rdata   = $rdata->with('bussinfo,companyinfo');
            $visible = array_merge(['companyinfo.Name', 'bussinfo.Name', 'bussinfo.Iphone'], $visible);
        } else if ($type == 'acco' || $type == 'mana' || $type == 'regulatory') {
            $rdata   = $rdata->with('bussinfo,companyinfo');
            $visible = array_merge(['companyinfo.Name', 'bussinfo.Name', 'bussinfo.Iphone', 'SettlementTime'], $visible);
        } else if ($type == 'hawa') {
            $company = Company::user_getinfo();
            if ($company == false) {
                return moerr('请先完善企业信息', '', 'gohawacreate');
            }
            $rdata   = $rdata->where('CompanyId', $company->CompanyId);
            $rdata   = $rdata->with('bussinfo');
            $visible = array_merge(['companyinfo.Name', 'bussinfo.Name', 'bussinfo.Iphone'], $visible);
        } else if ($type == 'hawaorder') {
            $rdata   = $rdata->with('contract_details');
            $rdata   = $rdata->hidden(['OperationLog']);
            $visible = ['ContractId', 'OrderNumber', 'CreateTime', 'StartTime', 'EndTime', 'State',
                'SurplusShipNum', 'SurplusUniversalDisposal', 'SurplusDisposalFee', 'ShipMoney',
                'DefaultPrice', 'DisposalFee', 'SettleRemark', 'contract_details'];
        }else if ($type == 'datascreen') {
            $rdata   = $rdata->with('bussinfo');
            $rdata   = $rdata->hidden(['OperationLog']);
            $visible = ['ContractId', 'OrderNumber', 'CreateTime', 'StartTime','PrintPassword', 'EndTime', 'State','bussinfo'=>['Name','Iphone']];
        }else if ($type == 'datascreen_regulatory') {
            $rdata   = $rdata->with('bussinfo');
            $rdata   = $rdata->hidden(['OperationLog']);
            $visible = ['ContractId', 'OrderNumber', 'CreateTime', 'StartTime','PrintPassword', 'EndTime', 'State','bussinfo'=>['Name','Iphone']];
        }else {
            return moerr('缺少参数');
        }
        $option = come_model_option($data, $rdata, $is_page);

        $rdata = $option['rdata'];
        $data  = $option['data'];

        if (!empty($data['field'])) {
            $rdata = $rdata->field($visible);
        }
        $rdata = $rdata->select();

        if (empty($data['field']) && !empty($visible)) {
            $rdata = $rdata->visible($visible);
        }

        $ndata['list']      = $rdata->toArray();
        $ndata['statetext'] = Contract::getStatusText();
        // $goodid = get_array_id($ndata,'GoodId','list','listinfo');
        if ($is_page) {
            $ndata['pageinfo'] = ['pageindex' => $data['pageindex'], 'pagemax' => $data['count']];
        }
        return $ndata;
    }

    /**
     * 获取信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function user_getinfo($cid = '', $userid = '', $hidden = ['ReInfo'])
    {

        if (!empty($cid)) {
            $data = Contract::where('ContractId', $cid)->find();
        } else {
            if (empty($userid)) {
                $userlogininfo = Pub::getuserid();
                $userid        = $userlogininfo['msg'];
            }
            $data = Contract::where('UserId', $userid)->find();
        }
        if (empty($data)) {
            return false;
        }
        $data->hidden($hidden);
        return $data;
    }

    /**
     * 获取状态
     * @param  [type] $list [id数组]
     * @return [type]       [返回错误代码]
     */
    public static function liststate($id, $hidden = [], $hidloag = true)
    {
        $data = Contract::where('State', '<>', Contract::STATEDELETE)->where('ContractId', $id)->find();
        if ($data->isEmpty()) {
            return moerr('没有找到您需要的订单');
        } else {
            //关联数据
            if ($hidloag) {
                $hidden = array_merge(['OperationLog'], $hidden);
                $data   = $data->hidden($hidden);
            } elseif (empty($hidden)) {
                $data = $data;
            } else {
                $data = $data->hidden($hidden);
            }
            return sok($data->toArray());
        }
    }

    /**
     * 获取订单信息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public static function getinfo($id, $type = 'acco')
    {
        if ($type == 'buss' || $type == 'hawa') {
            $data = self::liststate($id, ['SettlementTime', 'SettlementUserId', 'SettlementImg', 'SettlementNote']);
        } elseif ($type == 'mana') {
            $data = self::liststate($id, [], false);
        } else {
            $data = self::liststate($id);
        }
        if (!$data['code']) {
            return $data;
        }
        $rdata                = $data['msg'];

        //判断是否存在危废合同模板id
        if(!empty($rdata['TempId'])){
            $rdata['temp'] = ContractTemp::get($rdata['TempId']);
        }
            
        
        $rdata['companyinfo'] = Company::user_getinfo($rdata['CompanyId']);

        $rdata['ContractDetails'] = ContractDetails::where('ContractId', $id)->with(['goodinfo'])->select();
        //权限及其他数据
        if ($type == 'acco' || $type == 'mana') {
            $rdata['acco'] = (empty($rdata['SettlementUserId']) ? [] : User::getpublicinfo($rdata['SettlementUserId']));
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : User::getpublicinfo($rdata['BussinessId']));
            if (Rolepower::ispower(203008)) {
                $rdata['cost'] = Costtype::getcostlist($id, 'contract');
                if(!empty($rdata['RAPListId'])){
                   $sb = Raplist::getinfo($rdata['RAPListId'],'mana',false);
                   if($sb['code']){ $rdata['rap'] = $sb['msg'];}
                }
            }
        } else if ($type == 'hawa') {
            if ($rdata['companyinfo']['UserId'] !== Pub::userid()) {
                return moerr('没有权限');
            }
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : User::getpublicinfo($rdata['BussinessId']));
        } else if ($type == 'buss') {
            if ($rdata['BussinessId'] !== Pub::userid() && !Rolepower::ispower(204004)) {
                return moerr('没有权限');
            }
            $rdata['buss'] = (empty($rdata['BussinessId']) ? [] : User::getpublicinfo($rdata['BussinessId']));
        } else {
            return moerr('参数错误');
        }
        //判断是否打开了合同审批功能
        $rdata['switch_approval_contract'] = get_config_value('switch_approval_contract');

        $rdata['StateList'] = Contract::STATEARRAY;
        return ['code' => true, 'msg' => $rdata];
    }

    /**
     * 用户修改信息
     * @param  [type]  $data   [description]
     * @param boolean $wtnote [是否记录]
     * @return [type]          [description]
     */
    public static function user_reinfo($data, $wtnote = true)
    {
        if (empty($data['id'])) {
            return moerr('缺少重要参数');
        }
        $info     = Contract::get($data['id']);
        $userinfo = User::getinfo();
        $reinfo   = empty($info->OperationLog) ? '' : $info->OperationLog . "\n";
        $reinfo   = $reinfo . '【' . $userinfo->Name . '|' . $userinfo->UserId . '】在' . date('Y-m-d H:i', time()) . '进行了信息调整：';
        $nreinfo  = '';
        foreach ($data as $key => $value) {
            $sb = $info->getfiledname($key);
            if (empty($sb)) {
                continue;
            }
            //取原数据
            $ovalue = $info->$key;
            if ($key == 'State' && $value !== $ovalue) {
                $info->$key = $value;
                //value将改变成文字所以提前赋值
                $value   = $info->getStatusText((int) $value);
                $ovalue  = $info->getStatusText((int) $ovalue);
                $nreinfo = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
            } else if (is_numeric($value)) {
                if((int)$ovalue !== (int)$value){
                    $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                    $info->$key = $value;
                }
            } else if ((!empty($value) || is_numeric($value)) && $ovalue !== $value) {
                $nreinfo    = $nreinfo . '字段【' . $info->getfiledname($key) . '】由【' . $ovalue . '】修改为【' . $value . '】;' . "\n";
                $info->$key = $value;
            }
        }
        if (!empty($nreinfo)) {
            if ($wtnote) {
                $reinfo             = $reinfo . "\n" . $nreinfo;
                $info->OperationLog = $reinfo;
            }
            $info->save();
        } else {
            return true;
            // return moerr('没有找到需要调整的数据');
        }
    }

    public static function getfiledname($str)
    {
        $filename = ['OrderNumber' => '合同编号', 'State'        => '合同状态', 'StartTime'             => '生效时间',
            'EndTime'                  => '结束时间', 'ContractCost' => '合同费用', 'UpImg'                 => '图片附件', 'UpNote'          => '备注信息', 'SettlementTime'       => '结算时间', 'SettlementUserId'       => '结算审核人id', 'SettlementImg' => '结算时间',
            'SettlementNote'           => '结算凭证', 'BussinessId'  => '收集员ID', 'PartyAMailingAddress' => '甲方邮寄地址', 'PartyAContact' => '甲方联系人', 'PartyAContactMobile' => '甲方联系电话', 'PartyBMailingAddress' => '乙方邮寄地址', 'PartyBContact'  => '乙方联系人', 'PartyBContactMobile' => '乙方联系人电话', 'Identifier' => '统一识别码', 'Name' => '账户名称', 'Address' => '通讯地址', 'Mobile' => '联系电话', 'Bank' => '开户行名称', 'BankNum' => '银行账号', 'BankCode' => '开户行行号', 'UniversalDisposal' => '通用处置量', 'DisposalFee' => '预处置费', 'DefaultPrice' => '默认单价', 'ShipNum' => '运输次数', 'ShipMoney' => '运输费', 'SettleRemark' => '订单下单时备注','TempId'=>'合同模板','RAPListId'=>'挂账id'];
        if (empty($filename[$str])) {
            return false;
        }
        return $filename[$str];
    }

    /**
     * 获取统计数据
     * @return [type] [description]
     */
    public static function getsummary($date = '', $enddate = '')
    {
        if (empty($date)) {
            $date = date('Y-m-d', time());
        } else {
            $date = date('Y-m-d', strtotime($date));
        }
        if (empty($enddate)) {
            $rdata            = Contract::where('SettlementTime', '>', $date)->where('SettlementTime', '<=', $date . ' 24:00')->where('State', Contract::STATEOK)->field('sum(ContractCost) as Price,count(ContractId) as Count')->find();
            $rdata['timestr'] = mb_substr($date, 8, 2) . '号';
            $rdata['userlist'] = Contract::where('SettlementTime', '>', $date)->where('SettlementTime', '<=', $date . ' 24:00')->where('State', Contract::STATEOK)->field('BussinessId,sum(ContractCost) as Price,count(ContractId) as Count')->group('BussinessId')->select()->toArray();
        } else {
            $enddate = date('Y-m-d', strtotime($enddate));
            $rdata   = Contract::where('SettlementTime', '>', $date)->where('SettlementTime', '<=', $enddate . ' 24:00')->where('State', Contract::STATEOK)->field('sum(ContractCost) as Price,count(ContractId) as Count')->find();
            if (mb_substr($date, 5, 2) !== mb_substr($enddate, 5, 2)) {
                $rdata['timestr'] = mb_substr($date, 5, 5) . '~' . mb_substr($enddate, 6, 5);
            } else {
                $rdata['timestr'] = mb_substr($date, 8, 2) . '~' . mb_substr($enddate, 8, 2);
            }
            $rdata['userlist'] = Contract::where('SettlementTime', '>', $date)->where('SettlementTime', '<=', $enddate . ' 24:00')->where('State', Contract::STATEOK)->field('BussinessId,sum(ContractCost) as Price,count(ContractId) as Count')->visible(['BussinessId','Price','Count',])->group('BussinessId')->select()->toArray();
        }
        $rdata['CountUnit'] = '份';
        if ($rdata['Price'] > 1000) {
            $rdata['Price']     = $rdata['Price'] / 10000;
            $rdata['PriceUnit'] = '万元';
        } else {
            $rdata['PriceUnit'] = '元';
        }
        return $rdata;
    }

    /**
     * 获取选择的合同列表
     * @param $type
     * @param string $company_id
     * @param string $hawa_id
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function contractLists($type, $company_id = '', $hawa_id = '')
    {
        $where = [];
        if ($type == 1) {
            // 产废
            $company = Company::user_getinfo();
            $where[] = ['CompanyId', '=', $company['CompanyId']];
        }
        if ($type == 2) {
            // 收集
            $where[] = ['CompanyId', '=', $company_id];
        }
        if ($type == 3) {
            // 会计
            $hawa_info = HawaList::where('HawaListId', $hawa_id)->findOrEmpty();
            if (!empty($hawa_info['CompanyId'])) {
                $company = Company::where('CompanyId', $hawa_info['CompanyId'])->findOrEmpty();
                $where[] = ['CompanyId', '=', $company['CompanyId']];
            }

        }
        $contract = Contract::where($where)->where('State', Contract::STATECONFRIM)->select();
        return $contract;
    }

    /**
     * 合同额度抵扣
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function deduct($data)
    {
        //没有合同id 直接返回不抵扣
        if (empty($data['ContractId'])) {
            return moerr('缺少合同信息');
        }

        $sb = Contract::get($data['ContractId']);
        if (empty($sb)) {
            return moerr('没找到此合同信息');
        }

        if ($sb['CompanyId'] !== $data['CompanyId']) {
            return moerr('下单公司与合同签署单位不一致');
        }
        //合同信息检测
        //检测没问题后直接修改需要抵扣的量
        //但是到最后在进行保存
        $details      = [];
        $detailsindex = 0;
        if (!empty($data['Cont_Details'])) {
            foreach ($data['Cont_Details'] as $key => $value) {
                if (!empty($value['Cont_DedutNum'])) {
                    $details[$detailsindex] = ContractDetails::get($value['Id']);
                    if ($details[$detailsindex]['DeductType'] !== 1) {
                        return moerr('第' . ($key + 1) . '项货物不支持合同抵扣，请刷新页面从新获取合同信息');
                    }
                    if ($details[$detailsindex]['SurplusDedutNum'] < $value['Cont_DedutNum']) {
                        return moerr('第' . ($key + 1) . '项货物合同抵扣量不足以抵扣，请刷新页面从新获取合同信息');
                    }
                    $details[$detailsindex]->SurplusDedutNum = $details[$detailsindex]->SurplusDedutNum - $value['Cont_DedutNum'];
                    $detailsindex++;
                }
            }
        }

        //处置费
        if (!empty($data['Cont_DisposalFee'])) {
            if ($sb->SurplusDisposalFee < $data['Cont_DisposalFee']) {
                return moerr('处置费抵扣不足');
            }

            $sb->SurplusDisposalFee = $sb->SurplusDisposalFee - $data['Cont_DisposalFee'];
        }
        //运输次数
        if (!empty($data['Cont_SurplusShipNum'])) {
            if ($sb->SurplusShipNum < $data['Cont_SurplusShipNum']) {
                return moerr('运输次数抵扣不足');
            }
            $sb->SurplusShipNum = $sb->SurplusShipNum - $data['Cont_SurplusShipNum'];
        }
        //通用处置量
        if (!empty($data['Cont_UniversalDisposal'])) {
            if ($sb->SurplusUniversalDisposal < $data['Cont_UniversalDisposal']) {
                return moerr('通用处置量抵扣不足');
            }
            $sb->SurplusUniversalDisposal = $sb->SurplusUniversalDisposal - $data['Cont_UniversalDisposal'];
        }
        //保存修改的合同子项信息
        if ($detailsindex > 0) {
            foreach ($details as $key => $value) {
                $value->save();
            }
        }
        $sb->save();
    }

    /**
     * 取消所有抵扣
     * @param  [type] $data     [订单信息]
     * @return [type]           [description]
     */
    public static function canceldeduct($data)
    {
        //没有合同id 直接返回不抵扣
        if (empty($data['ContractId'])) {
            return moerr('缺少原合同信息');
        }

        $sb = Contract::get($data['ContractId']);
        if (empty($sb)) {
            return moerr('没找到原合同信息');
        }

        if ($sb['CompanyId'] !== $data['CompanyId']) {
            return moerr('下单公司与合同签署单位不一致');
        }
        $datainfo = Hawa::where('HawaListId', $data['HawaListId'])->select();
        //合同信息检测
        //检测没问题后直接修改需要抵扣的量
        //但是到最后在进行保存

        foreach ($datainfo as $key => $value) {
            if (!empty($value['Cont_DedutNum'])) {
                $cond = ContractDetails::get($value['Cont_Id']);
                //将合同抵扣项恢复
                $cond->SurplusDedutNum = $cond->SurplusDedutNum + $value['Cont_DedutNum'];
                $cond->save();
                //取消此项的抵扣
                Hawa::where('HawaId', $value['HawaId'])->update(['Cont_DedutNum' => null, 'Cont_Id' => null]);
            }
        }

        //处置费
        if (!empty($data['Cont_DisposalFee'])) {
            $sb->SurplusDisposalFee = $sb->SurplusDisposalFee + $data['Cont_DisposalFee'];
        }
        //运输次数
        if (!empty($data['Cont_SurplusShipNum'])) {
            $sb->SurplusShipNum = $sb->SurplusShipNum + $data['Cont_SurplusShipNum'];
        }
        //通用处置量
        if (!empty($data['Cont_UniversalDisposal'])) {
            $sb->SurplusUniversalDisposal = $sb->SurplusUniversalDisposal + $data['Cont_UniversalDisposal'];
        }
        //保存修改的信息
        $sb->save();
    }

}
